package com.itheima.aop;

import com.itheima.Mapper.OperateLogMapper;
import com.itheima.utils.CurrentHolder;
import org.json.JSONObject;
import com.itheima.Pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(com.itheima.annotation.LogOperation)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 操作人ID - 当前登录员工ID
        // 获取请求头中的jwt令牌，解析令牌
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer operateUser = (Integer) claims.get("id");
        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        // 操作类名
        String className = joinPoint.getTarget().getClass().getName();
        // 操作方法名
        String methodName = joinPoint.getSignature().getName();
        // 操作参数名
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);
        // 操作耗时
        // 开始时间
        long startTime = System.currentTimeMillis();
        // 原始方法运行
        Object result = joinPoint.proceed();
        // 结束时间
        long endTime = System.currentTimeMillis();
        // 操作方法返回值
        String returnValue = JSONObject.valueToString(result);
        long costTime = endTime - startTime;
        log.info("操作耗时：{}",costTime);
        // 记录操作日志
        OperateLog operateLog = new OperateLog(getCurrentUserId(),operateUser,operateTime,className,methodName,methodParams,
                returnValue,costTime);
        operateLogMapper.insert(operateLog);
        log.info("AOP记录操作日志：{}",operateLog);
        return result;
    }
    private int getCurrentUserId() {
        return CurrentHolder.getCurrentId();
    }
}
